<?php
declare (strict_types=1);

namespace app\command;

use app\api\logic\LogicalProcess;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;


class Explore extends Command
{
    protected function configure()
    {
        $this->setName('app\command\Explore');

    }

    //游历结算逻辑
    protected function execute(Input $input, Output $output)
    {
        //查询用户游历记录
        $explore = Db::name("explore_record")->where("is_over", 0)->field(['user_id as userId', 'SUM(all_get_amount) as allAmount', 'SUM(price) as price'])->group('user_id')->select();
        if (empty($explore)) {
            $output->writeln('null');
            exit;
        }
        //查询用户联盟等级


        foreach ($explore as $v) {
            //结算游历
            (new LogicalProcess())->wallletChange($v['user_id'], bcdiv($v['allAmount'], '30', 6), 9, 1, 2, "游历结算经书");
            //分销结算
            //查询上级用户信息
            $user = Db::name("member")->where("id", $v['user_id'])->field("id,lv,group")->find();
            $userLvInfo = Db::name("league_config")->where("league_lv", $user['lv'])->find();
            if (!$user['group'] == 0 || !empty($user['group'])) {
                //转为数组
                $group = explode(",", $user['group']);
                foreach ($group as $pid) {
                    //查询上级用户等级
                    $parentLv = Db::name("member")->where("id", $pid)->value("lv");
                    if ($parentLv < $user['lv']) break;
                    //查询上级用户等级信息
                    $parentLvInfo = Db::name("league_config")->where("league_lv", $parentLv)->find();
                    $diffNum = 0;
                    if ($parentLv > $user['lv']) {
                        $diffNum = bcdiv($parentLvInfo['explore'] - $userLvInfo['explore'], "100", 6);
                    } else {
                        $diffNum = bcdiv($parentLvInfo['explore'], '100');
                    }
                    $subtract = bcmul(bcsub($v['allAmount'], $v['price'], 6), $diffNum);
                    (new LogicalProcess())->wallletChange($pid, $subtract, 8, 1, 1, '唐僧游历获得经书');
                }
            }
        }
        //给所有正在游历的马匹游历天数+1,收益+1天
        Db::name('explore_record')
            ->where('is_over', 0)
            ->update([
                'explore_days' => Db::raw('explore_days + 1'),
                'has_books'    => Db::raw('all_get_amount / 30 + has_books')
            ]);
        //如果有大于等于30的游历天数,则将马匹状态设置为失效
        Db::name('explore_record')
            ->where('explore_days', '>=', 30)
            ->update(['is_over' => 1]);

        $output->writeln('success');
        exit;
    }
}